import fg from "fast-glob";
import fs from "fs-extra";
import path from "path";
import { UnityHelper } from "./UnityHelper.js";
import { PrefabSearcher } from "./PrefabSearcher.js";
import { toolchain } from "../toolchain.js";

export class UsingLegacy {

    public async lookUp(): Promise<void> {
        if (toolchain.opts.input == null) {
            console.error('no input specified!');
            process.exit(1);
        }
        const legacyRoot = path.join(toolchain.opts.projectRoot, toolchain.opts.input);
        const imgs = await fg(['**/*.png', '**/*.jpg'], { cwd: legacyRoot });
        const legacyGUIDs: string[] = [];
        const guidImgMap: { [guid: string]: string } = {};
        for (const img of imgs) {
            const file = path.join(legacyRoot, img);
            const guid = await UnityHelper.readGUID(file + '.meta');
            legacyGUIDs.push(guid);
            guidImgMap[guid] = img;
        }

        let out: string = '';
        const uiRoot = path.join(toolchain.opts.projectRoot, 'Assets/AssetSources/ui');
        const prefabs = await fg('**/*.prefab', { cwd: uiRoot });
        for (const p of prefabs) {
            const file = path.join(uiRoot, p);
            const searcher = new PrefabSearcher();
            const usages = await searcher.findImageUsages(file, legacyGUIDs);
            if (usages.length > 0) {
                out += p + '\n';
                for (const u of usages) {
                    console.warn(p, u.path, guidImgMap[u.image]);
                    out += u.path + '  ' + guidImgMap[u.image] + '\n';
                }
                out += '-----------\n'
            }

            // const content = await fs.readFile(file, 'utf-8');
            // const us: string[] = [];
            // for (const g of legacyGUIDs) {
            //     if (content.includes(g)) {
            //         console.warn(p, guidImgMap[g], g);
            //         us.push(guidImgMap[g]);
            //     }
            // }
            // if (us.length > 0) {
            //     out += p;
            //     out += us.join('\n');
            //     out += '-----------\n'
            // }
        }

        await fs.writeFile(toolchain.opts.output!, out, 'utf-8');
    }
}
